//
//  contentView.m
//  微博2期
//
//  Created by J on 15/11/22.
//
//

#import "DropDownMenu.h"
@interface DropDownMenu()
/**
 *  将来 用来显示具体内容的容器
 */
@property(nonatomic,weak) UIImageView *contentView;//ui控件一般用strong因为 会addSubView强引用 不过懒加载只能用强指针
//或者创建出来之后直接addSubview后再用弱指针指向它
@end
@implementation DropDownMenu


//懒加载
- (UIImageView *)contentView{
    if (!_contentView) {
        //添加带箭头的灰色图片
        UIImageView * contentView  = [[UIImageView alloc]init];
        contentView.image = [UIImage imageNamed:@"popover_background"];//垂直拉伸
//        contentView.width = 217;//图片原始宽度

        //        contentView.y = 200;
        [self addSubview:contentView];
        contentView.userInteractionEnabled = YES;
        self.contentView = contentView;//弱指针 前面需要 addSubview 不然会被释放  这里是调用set方法
    }
    return _contentView;
}




- (instancetype)initWithFrame:(CGRect)frame{
    
    if (self = [super initWithFrame:frame]) {

        //添加蒙板
        self.backgroundColor = [UIColor clearColor];
               [self.contentView addSubview:[UIButton buttonWithType:UIButtonTypeContactAdd]];
        [self  addSubview:self.contentView]; //添加到应用程序的窗口上

    }
    
    return self;
}


+ (instancetype)menu{
    
    return [[self alloc]init];
    
}

//显示
- (void)showFrom:(UIView *)from{
    
    NSLog(@"%@",from);
    //获得最上面的窗口
    UIWindow *window = [[UIApplication sharedApplication].windows lastObject];
    //添加自己到window
    [window addSubview:self];
    //设置尺寸
    self.frame = window.bounds;//window 默认全屏  先创建 后设置尺寸
    
    //4.调整灰色图片的位置
   
    //默认情况下frame是以父控件左上角为坐标原点
    //可以通过转换坐标原点 改变frame的参照点

   CGRect newframe =  [from convertRect:from.bounds toView:nil];//nil==window //将convertRect 从左边坐标系 转为右边的坐标系计来计算 返回心frame
    
    
    self.contentView.centerX = CGRectGetMidX(newframe);
    self.contentView.y = newframe.origin.y+newframe.size.height;
    
}


//销毁
- (void)dismiss{
    [self removeFromSuperview];
}


- (void)setContent:(UIView *)content{
    
    _content = content;
    _content.x = 10;
    _content.y =15;
    //设置菜单的尺寸
    //设置内容宽度   contentView只是一个图片
//    content.width = self.contentView.width-2*content.x;//设置内容的宽度为图片的宽度减去左右边距 内容view宽度给的是0
    
    
    self.contentView.width = CGRectGetMaxX(content.frame)+10;
    
    //添加内容到灰色图片中
    self.contentView.height = CGRectGetMaxY(content.frame)+12;//设置背景高度为内容view高度加上上边距

    
    [self.contentView addSubview:content];
    
    
}

- (void)setContentViewcontroller:(UIViewController *)contentViewcontroller{
    
    _contentViewcontroller = contentViewcontroller;
    self.content = contentViewcontroller.view;
    
    
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self dismiss];
    
}
@end
